package org.example.projectdemo.service;

import org.example.projectdemo.model.entity.Attendance;
import org.example.projectdemo.model.entity.Student;
import org.example.projectdemo.model.entity.Schedule;
import org.example.projectdemo.repository.AttendanceRepository;
import org.example.projectdemo.repository.StudentRepository;
import org.example.projectdemo.repository.ScheduleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * ClassName: AttendanceService
 * Package: org.example.projectdemo.service.impl
 * Description:
 *
 * @Author ZY
 * @Create 23:08
 * @Version 1.0
 */
@Service// 标记这是一个业务服务组件，可被Spring注入
public class AttendanceService {
    @Autowired// 自动注入Repository
    private AttendanceRepository attendanceRepository;
    
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private ScheduleRepository scheduleRepository;

    // 创建考勤记录
    public Attendance createAttendance(Attendance attendance) {
        // 确保ID为null以创建新记录
        attendance.setId(null);
        return attendanceRepository.save(attendance);
    }

    // 更新考勤记录
    public Attendance updateAttendance(Attendance attendance) {
        // 确保ID存在以更新记录
        if (attendance.getId() == null || !attendanceRepository.existsById(attendance.getId())) {
            throw new IllegalArgumentException("考勤记录ID不存在，无法更新");
        }
        return attendanceRepository.save(attendance);
    }

    // 根据ID查找考勤记录
    public Optional<Attendance> getAttendanceById(Long id) {//Optional<T>：用于处理可能为null的查询结果，避免空指针异常。
        return attendanceRepository.findById(id);
    }

    // 检查考勤记录是否存在
    public boolean existsAttendanceById(Long id) {
        return attendanceRepository.existsById(id);
    }

    // 查找所有考勤记录
    public List<Attendance> getAllAttendances() {
        return attendanceRepository.findAll();
    }

    // 根据学生ID查找考勤记录
    public List<Attendance> getAttendancesByStudentId(Long studentId) {
        return attendanceRepository.findByStudentId(studentId);
    }

    // 根据排课ID查找考勤记录
    public List<Attendance> getAttendancesByScheduleId(Long scheduleId) {
        return attendanceRepository.findByScheduleId(scheduleId);
    }

    // 根据学生ID和排课ID查找特定考勤记录
    public Optional<Attendance> getAttendanceByStudentAndSchedule(Long studentId, Long scheduleId) {
        return attendanceRepository.findByStudentIdAndScheduleId(studentId, scheduleId);
    }

    // 删除考勤记录
    public void deleteAttendance(Long id) {
        attendanceRepository.deleteById(id);
    }
    
    // 批量创建考勤记录
    @Transactional
    public List<Attendance> batchCreateAttendance(Long scheduleId, LocalDate attendanceDate, List<Map<String, Object>> studentAttendances) {
        List<Attendance> createdAttendances = new ArrayList<>();
        
        try {
            // 获取排课信息
            Schedule schedule = scheduleRepository.findById(scheduleId)
                    .orElseThrow(() -> new RuntimeException("排课不存在，ID: " + scheduleId));
            
            System.out.println("开始批量创建考勤记录，排课ID: " + scheduleId + ", 日期: " + attendanceDate);
            
            for (Map<String, Object> studentAttendance : studentAttendances) {
                try {
                    // 安全地获取值，避免null值异常
                    Object studentIdObj = studentAttendance.get("studentId");
                    Object statusObj = studentAttendance.get("status");
                    Object remarkObj = studentAttendance.get("remark");
                    
                    if (studentIdObj == null || statusObj == null) {
                        System.err.println("学生ID或状态为空，跳过该记录: " + studentAttendance);
                        continue;
                    }
                    
                    Long studentId = Long.valueOf(studentIdObj.toString());
                    String statusStr = statusObj.toString();
                    String remark = remarkObj != null ? remarkObj.toString() : null;
                    
                    // 获取学生信息
                    Student student = studentRepository.findById(studentId)
                            .orElseThrow(() -> new RuntimeException("学生不存在，ID: " + studentId));
                    
                    // 检查是否已存在考勤记录
                    Optional<Attendance> existingAttendance = attendanceRepository.findByStudentIdAndScheduleId(studentId, scheduleId);
                    
                    Attendance attendance;
                    if (existingAttendance.isPresent()) {
                        // 更新现有记录
                        attendance = existingAttendance.get();
                        attendance.setAttendanceDate(attendanceDate);
                        attendance.setStatus(Attendance.AttendanceStatus.valueOf(statusStr));
                        attendance.setRemark(remark);
                        System.out.println("更新考勤记录，学生ID: " + studentId + ", 状态: " + statusStr);
                    } else {
                        // 创建新记录
                        attendance = new Attendance();
                        attendance.setStudent(student);
                        attendance.setSchedule(schedule);
                        attendance.setAttendanceDate(attendanceDate);
                        attendance.setStatus(Attendance.AttendanceStatus.valueOf(statusStr));
                        attendance.setRemark(remark);
                        System.out.println("创建考勤记录，学生ID: " + studentId + ", 状态: " + statusStr);
                    }
                    
                    attendance = attendanceRepository.save(attendance);
                    createdAttendances.add(attendance);
                    
                } catch (Exception e) {
                    System.err.println("处理学生考勤记录失败: " + e.getMessage());
                    e.printStackTrace();
                    // 继续处理其他学生，不中断整个批量操作
                }
            }
            
            System.out.println("批量考勤记录创建完成，成功: " + createdAttendances.size() + " 条");
            return createdAttendances;
            
        } catch (Exception e) {
            System.err.println("批量创建考勤记录失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("批量创建考勤记录失败: " + e.getMessage(), e);
        }
    }
}